package org.appfuse.service.impl;

/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.providers.ldap.LdapAuthoritiesPopulator;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.ldap.LdapUserDetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.appfuse.dao.UserDao;


public class DatatbaseAuthoritiesPopulator implements LdapAuthoritiesPopulator {
   //~ Static fields/initializers =====================================================================================

   private static final Log logger = LogFactory.getLog(DatatbaseAuthoritiesPopulator.class);
   
   private UserDao dao;

   /**
    * Set the Dao for communication with the data layer.
    * @param dao
    */
   public void setUserDao(UserDao dao) {
       this.dao = dao;
   }


   //~ Instance fields ================================================================================================

   /**
    * A default role which will be assigned to all authenticated users if set
    */

   /**
    * Obtains the authorities for the user who's directory entry is represented by
    * the supplied LdapUserDetails object.
    *
    * @param userDetails the user who's authorities are required
    * @return the set of roles granted to the user.
    */
   public final GrantedAuthority[] getGrantedAuthorities(LdapUserDetails userDetails) {
       String userDn = userDetails.getDn();

       if (logger.isDebugEnabled()) {
           logger.debug("Getting authorities for user " + userDn);
       }

       UserDetails ud = dao.loadUserByUsername(userDetails.getUsername());
       GrantedAuthority[] roles = new GrantedAuthority[0];
       if (ud != null){
    	   roles = ud.getAuthorities();
       }
      
       return (GrantedAuthority[]) roles;
   }

}
